<template>
    <a-menu
      v-model:open-keys="state.openKeys"
      v-model:selected-keys="state.selectedKeys"
      :inline-collapsed="collapsed"
      mode="inline"
      theme="dark"
      >
      <template v-for="m in routes" :key="m.path">
        <a-sub-menu v-if="m.children && m.children.length >= 1" key="m.path">
            <template #title><i class="el-icon-menu"></i>{{ m.meta.title }}</template>
            <a-menu-item v-for="child in m.children" :index="child.path" :key="child.path" @click="handleRoute(child)">{{ child.meta.title }}</a-menu-item>
        </a-sub-menu>
        <a-menu-item v-else @click="handleRoute(m)">{{ m.meta.title }}</a-menu-item>
      </template>
    </a-menu>
</template>
<script>
import { reactive, toRefs, ref, watch } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
export default {
  setup() {
    const store = useStore();
    const routes = ref(store.getters.routes);
    const collapsed = ref(false);
    const router = useRouter();
    const currentRoute = useRoute();
    const state = reactive({
      openKeys: getOpenKeys(),
      selectedKeys: [currentRoute.path]
    });

    const getOpenKeys = () => {
      currentRoute.matched.slice(1).map(n => n.path);
    };

    const handleRoute = menu => {
      router.push(menu.path);
    };

    // 监听菜单收缩状态
    watch(
      () => collapsed,
      newVal => {
        state.openKeys = newVal ? [] : getOpenKeys();
        state.selectedKeys = [currentRoute.path];
      }
    );

    // 跟随页面路由变化，切换菜单选中状态
    watch(
      () => currentRoute.fullPath,
      () => {
        if (currentRoute.path == "login" || collapsed) return;
        state.openKeys = getOpenKeys();
        state.selectedKeys = [currentRoute.path];
      }
    );

    return {
      ...toRefs(state),
      routes,
      collapsed,
      handleRoute
    };
    // computed: {
    //   routes() {
    //     console.log(this.$store.getters.routes);
    //     return this.$store.getters.routes;
    //   }
    // },
    // methods: {
    //   handleRoute(menu) {
    //     this.$router.push(menu.path);
    //   }
    // }
  }
};
</script>
<style>
</style>